// import * as puppeteer from 'puppeteer';
// import * as QRCode from 'qrcode';
import { BrowserWindow } from 'electron';
import { AccountService } from './account-service';
import { PlatformService } from './platform-service';

interface QRSession {
  id: string;
  platform: string;
  status: 'pending' | 'scanning' | 'success' | 'failed';
  qrCode?: string;
  token?: string;
  username?: string;
}

export class AuthService {
  private sessions: Map<string, QRSession> = new Map();
  private accountService: AccountService;
  private platformService: PlatformService;

  constructor() {
    this.accountService = new AccountService();
    this.platformService = new PlatformService();
  }

  async startQRLogin(platform: string): Promise<{ sessionId: string; qrCode: string }> {
    const sessionId = this.generateSessionId();
    const session: QRSession = {
      id: sessionId,
      platform,
      status: 'pending',
    };

    this.sessions.set(sessionId, session);

    // 生成二维码
    const qrData = `login-${platform}-${sessionId}`;
    const qrCode = `data:image/svg+xml;base64,${Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="white"/><text x="100" y="100" text-anchor="middle" font-size="12">QR Code: ${qrData}</text></svg>`).toString('base64')}`;

    // 启动浏览器进行模拟登录
    this.simulateLoginProcess(sessionId, platform);

    return { sessionId, qrCode };
  }

  async getLoginStatus(sessionId: string): Promise<QRSession> {
    const session = this.sessions.get(sessionId);
    if (!session) {
      throw new Error('Session not found');
    }
    return session;
  }

  private async simulateLoginProcess(sessionId: string, platform: string) {
    const session = this.sessions.get(sessionId);
    if (!session) return;

    session.status = 'scanning';
    
    try {
      // 这里模拟扫码登录过程
      // 实际实现中，这里应该使用 Puppeteer 控制浏览器进行真实的登录流程
      
      // 模拟等待扫码
      await this.delay(3000);
      
      // 模拟获取token
      const mockToken = `mock-token-${platform}-${Date.now()}`;
      const mockUsername = `user-${Math.floor(Math.random() * 1000)}`;
      
      session.status = 'success';
      session.token = mockToken;
      session.username = mockUsername;

      // 保存账号信息
      const platformData = await this.platformService.getPlatforms();
      const targetPlatform = platformData.find(p => p.name === platform);
      
      if (targetPlatform) {
        await this.accountService.addAccount({
          platformId: targetPlatform.id,
          username: mockUsername,
          token: mockToken,
          isActive: true
        });
      }

    } catch (error) {
      session.status = 'failed';
      console.error('Login failed:', error);
    }
  }

  private async delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  private generateSessionId(): string {
    return Math.random().toString(36).substring(2, 15);
  }

  /**
   * 获取平台登录URL用于前端显示
   * @param platform 平台名称
   * @returns 登录URL
   */
  async openBrowserLogin(platform: string): Promise<{ loginUrl: string }> {
    try {
      console.log(`[AuthService] 正在为平台 ${platform} 获取登录URL...`);
      
      // 获取平台登录URL
      const loginUrl = this.getPlatformLoginUrl(platform);
      console.log(`[AuthService] 登录URL: ${loginUrl}`);
      
      if (!loginUrl) {
        throw new Error(`无法获取平台 ${platform} 的登录URL`);
      }
      
      return { loginUrl };
      
    } catch (error) {
      console.error(`[AuthService] 获取登录URL失败:`, error);
      throw error;
    }
  }

  /**
   * 获取平台登录URL
   * @param platform 平台名称
   */
  private getPlatformLoginUrl(platform: string): string {
    const urls: { [key: string]: string } = {
      'douyin': 'https://creator.douyin.com/',
      'bilibili': 'https://passport.bilibili.com/login',
      'xiaohongshu': 'https://creator.xiaohongshu.com/login'
    };
    
    return urls[platform] || 'https://www.google.com';
  }

  /**
   * 获取平台显示名称
   * @param platform 平台名称
   */
  private getPlatformDisplayName(platform: string): string {
    const names: { [key: string]: string } = {
      'douyin': '抖音',
      'bilibili': '哔哩哔哩',
      'xiaohongshu': '小红书'
    };
    
    return names[platform] || platform;
  }

  /**
   * 检查URL是否表示登录成功
   * @param platform 平台名称
   * @param url 当前URL
   */
  private isLoginSuccessUrl(platform: string, url: string): boolean {
    const successPatterns: { [key: string]: string[] } = {
      'douyin': ['creator.douyin.com/creator-micro', 'creator.douyin.com/content'],
      'bilibili': ['space.bilibili.com', 'member.bilibili.com'],
      'xiaohongshu': ['creator.xiaohongshu.com/publish']
    };
    
    const patterns = successPatterns[platform] || [];
    return patterns.some(pattern => url.includes(pattern));
  }

  /**
   * 从Cookie中提取认证信息
   * @param platform 平台名称
   * @param cookies Cookie数组
   */
  private extractAuthInfo(platform: string, cookies: Electron.Cookie[]): { token?: string; username?: string } {
    const authInfo: { token?: string; username?: string } = {};
    
    // 根据不同平台提取不同的认证Cookie
    switch (platform) {
      case 'douyin':
        const douyinToken = cookies.find(c => c.name === 'sessionid' || c.name === 'sid_guard');
        if (douyinToken) {
          authInfo.token = douyinToken.value;
        }
        break;
        
      case 'bilibili':
        const biliToken = cookies.find(c => c.name === 'SESSDATA');
        if (biliToken) {
          authInfo.token = biliToken.value;
        }
        break;
        
      case 'xiaohongshu':
        const xhsToken = cookies.find(c => c.name === 'web_session');
        if (xhsToken) {
          authInfo.token = xhsToken.value;
        }
        break;
    }
    
    // 尝试从Cookie中提取用户名
    const usernameCookie = cookies.find(c => 
      c.name.toLowerCase().includes('username') || 
      c.name.toLowerCase().includes('user') ||
      c.name.toLowerCase().includes('name')
    );
    
    if (usernameCookie) {
      authInfo.username = usernameCookie.value;
    } else {
      // 如果没有找到用户名，生成一个默认的
      authInfo.username = `${platform}_user_${Date.now()}`;
    }
    
    return authInfo;
  }

  /**
   * 保存从浏览器获取的账号信息
   * @param platform 平台名称
   * @param authInfo 认证信息
   */
  private async saveAccountFromBrowser(platform: string, authInfo: { token?: string; username?: string }): Promise<void> {
    try {
      const platformData = await this.platformService.getPlatforms();
      const targetPlatform = platformData.find(p => p.id === platform);
      
      if (targetPlatform && authInfo.token) {
        await this.accountService.addAccount({
          platformId: targetPlatform.id,
          username: authInfo.username || `${platform}_user_${Date.now()}`,
          token: authInfo.token,
          isActive: true
        });
        
        console.log(`${platform} 账号已成功保存到数据库`);
      } else {
        throw new Error(`未找到平台 ${platform} 或认证信息无效`);
      }
    } catch (error) {
      console.error(`保存 ${platform} 账号信息失败:`, error);
      throw error;
    }
  }

  // 模拟抖音登录过程
  private async performDouyinLogin(sessionId: string) {
    console.log('Starting Douyin login simulation for session:', sessionId);
    
    try {
      // 模拟登录延迟
      await this.delay(2000);
      
      const session = this.sessions.get(sessionId);
      if (session) {
        session.status = 'success';
        session.token = 'mock_douyin_token_' + Date.now();
        session.username = 'douyin_user_' + Math.random().toString(36).substr(2, 5);
      }
      
    } catch (error) {
      console.error('Douyin login simulation failed:', error);
      const session = this.sessions.get(sessionId);
      if (session) {
        session.status = 'failed';
      }
    }
  }
}
